package com.loan.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.loan.exeception.AppException;
import com.loan.exeception.AppExceptionCodeMsg;
import com.loan.service.SendSmsService;
//import com.thx.service.AliYunSmsService;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @author z
 */
@Service
public class SendSmsServiceImpl implements SendSmsService {
//    @Resource
//    private AliYunSmsService aliYunSmsService;
    @Resource
    private RedisTemplate<String, String> redisTemplate;
    @Override
    public boolean sendSms(String phone) {
        if (phone.matches("1[3-9]\\d{9}")) {
            // 是有效的中国大陆手机号码
            //随机生成验证码
            String code= RandomUtil.randomNumbers(4);
//            boolean b = aliYunSmsService.sendSms(phone, code, "张冲个人博客", "SMS_460710573");
//            if (b){
                //将生成的验证码缓存到redis中，并且设置有效期5min
                redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
            }else {
                throw new AppException(AppExceptionCodeMsg.SEND_MESSAGE_IS_ERROR);
            }
//        }else {
//            throw new AppException(AppExceptionCodeMsg.PHONE_NUMBER_IS_ILLEGAL);
//        }
        return true;
    }

    @Override
    public boolean checkSms(String phone, String code) {
        //判断是否输入手机号码
        if (phone==null || "".equals(phone)){
            throw new AppException(AppExceptionCodeMsg.PHONE_NUMBER_IS_NULL);
        }else {
        //判断手机格式是否正确
        if (phone.matches("1[3-9]\\d{9}")) {
            // 是有效的中国大陆手机号码
            //从redis中获取缓存的验证码
            Object codeInRedis = redisTemplate.opsForValue().get(phone);
            //进行验证码的比对（如果比对成功则进行插入数据库操作）
            if (codeInRedis != null && codeInRedis.equals(code)){
                return true;
            }
        }
        return false;
        }

    }

    @Override
    public boolean sendSmsNull(String phone) {
        //随机生成验证码
        //String code= RandomUtil.randomNumbers(4);
        String code= "1234";
        //将生成的验证码缓存到redis中，并且设置有效期5min
        redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
        return true;
    }
}
